package com.lwl.blog.controller;

import com.lwl.blog.listener.ThymeleafListener;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/PageServlet/*")
public class PageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.通过请求地址获得跳转页面
        String s = request.getRequestURI().replaceAll("/PageServlet/", "");

        //2.因为使用来了thymeleaf的方式写了页面跳转的，所以需要使用它特有的方式解析
        String replace = s.replace(".html", "");
        //3.获取上下文对象
        ServletContext servletContext = request.getServletContext();
        //4.获得模板引擎对象
        TemplateEngine templateEngine= ThymeleafListener.getTemplateEngine(servletContext);

        //5.创建一个模板引擎对象,将跳转的数据带到模板引擎对象中
        WebContext webContext=new WebContext(request,response,servletContext);
        //6.用模板引擎对象的的独有的方法跳转到指定页面
        templateEngine.process(replace,webContext,response.getWriter());

    }
}
